<template>

	<view class="setUpChildLogin ">
		<view class="flex-column">
			<view class="margin-bottom_30rpx font-weight font-size_44rpx" v-if="step==1">
				欢迎来到搭子公众号
			</view>

			<text v-if="step==1" style="color: #666666;">开始介绍自己</text>

			<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
				<image v-if="!form.avatarUrl" class="loginAvatar" :src="Uploadavatar" mode=""></image>
				<image v-else class="loginAvatar" :src="form.avatarUrl" mode=""></image>

			</button>




			<view class="flex margin-top_40rpx" v-if="step==2">
				<view class="font-size_44rpx">
					你好！
				</view>
				<view class="font-size_44rpx" style="color: #6C02FA;">
					微信昵称称呼
				</view>
			</view>
			<view class="margin-top_20rpx margin-bottom_50rpx" v-if="step==2">
				<text style="color: #666666;">定位所在城市，能够快速获取周边搭子</text>
			</view>

		</view>

		<view v-if="step==1">
			<view class="margin_40rpx_0">
				性别
			</view>
			<view class="flex-between">


				<block v-for="(item,index) in Gender" :key="index">
					<view :class="currentIndex==index?'male flex':'female flex'" @click="switchGenderFn(index)">
						<image v-if="index==0" class="genderImg" :src="nanicon" mode=""></image>
						<image v-if="index==1" class="genderImg" :src="womenticon" mode=""></image>
						{{item}}
					</view>
					<!-- 	<view class="female flex">
						女生
					</view> -->
				</block>
			</view>
		</view>
		<block v-if="step==1">
			<view class="margin_40rpx_0">
				生日
			</view>
			<view class="birthday flex" style="color: rgb(153, 153, 153);">
				<picker mode="date" :value="date" @change="bindDateChange">
					<view class="flex-align-center color6" v-if="isShowBirthday">
						{{ yeartime }}
						<text>-</text>
						{{ monthtime }}
						<text>-</text>
						{{ daytime }}
					</view>
					<view v-else>请选择你的生日</view>
				</picker>


			</view>
		</block>
		<form @submit="handleSubmit">
<!-- 
			<block v-if="step==1">
				<view class="margin_40rpx_0">
					当前位置
				</view>
				<view class="birthday text-align_center flex" style="color: rgb(153, 153, 153); "
					@click="getLocations()">
					<view class="font-overflow" style="width: 400rpx;">{{address?address:'点击获取附近位置'}}</view>

				</view>
			</block> -->
			<block v-if="step==1">

				<!-- <view class="margin_40rpx_0">
					昵称
				</view>
				<view class="birthday flex  ">
			
					<input v-model="form.nickname" type="nickname" name="nickname" placeholder="点击选择昵称" />
			
				</view> -->

				<view class="margin_40rpx_0">
					手机号
				</view>

				<view class="getPhone flex  ">

					<input v-model="form.phone" type="number" maxlength="11" name="phone" placeholder="请输入手机号" />

					<!-- <button type="primary" size="mini" class="ckPhone" open-type="getPhoneNumber"
						@getphonenumber="onGetPhoneNumber">获取手机号</button> -->


				</view>



			</block>
			<view >
				<view class="margin_40rpx_0">
					验证码
				</view>
				<view class="getPhone flex  ">
				
					<input v-model="form.sms_code" type="number" maxlength="11" name="phone" placeholder="请输入验证码" />
				
					<!-- <button type="primary" size="mini" class="ckPhone" open-type="getPhoneNumber"
						@getphonenumber="onGetPhoneNumber">获取手机号</button> -->
				 <view class="verificationCode" @click="getVerificationCode()" >{{ count ? count + '秒' : '获取验证码' }}</view>
				
				</view>
			
				
			</view>
			<block v-if="step==2">
				<view class="margin_40rpx_0">
					手机号
				</view>

				<view class="getPhone flex  ">

					<input v-model="form.phone" type="number" maxlength="11" name="phone" placeholder="请输入手机号" />

					<!-- <button type="primary" size="mini" class="ckPhone" open-type="getPhoneNumber"
						@getphonenumber="onGetPhoneNumber">获取手机号</button> -->


				</view>

			</block>

			<view style="text-align: center;"><button type="primary" form-type="submit" size="mini" class="next ">
					{{step==1?'确定':'确定'}}</button></view>
					
					
			<!-- 	<view class="next flex" @click="nextFn()">
			   下一步
			</view> -->
		
		</form>
		<sunui-popup ref="myPackagePopup">
			<template v-slot:content>
		
				<view class="flex-column ">
					<scroll-view :scroll-y="true" style="height: 1000rpx;">
						<view style="text-align: center; margin-bottom: 20rpx;">
							注册协议
						</view>
						<rich-parser :html="basicConfiguration.register_notice"
							domain="https://6874-html-foe72-1259071903.tcb.qcloud.la" lazy-load ref="article"
							selectable show-with-animation use-anchor lazyLoad="true"></rich-parser>
						<!-- 	<view v-html="transaction_rule" class="">
		
						</view> -->
					</scroll-view>
				</view>
		
			</template>
		</sunui-popup>
	   <radio-group name="apply" class="radioText flex-start-center protocol" :class="'animation-' + animation"
	   	@click="checkedOn2()">
	   
	   	<label @click.stop="checkedOn2()">
	   		<view class="flex-start-center">
	   			<radio :checked="agreeChecked" value="1" color="#A265FC"
	   				style="transform:scale(0.8);padding-left:12rpx;" />
	   			<view class=" flex ">
	   				<text>充值即同意 <text style="color: #A265FC;"
	   						@click.stop="toAgreement()">《用户充值协议》</text>，如遇到问题，点击
	   					<text style="color: #A265FC;"
	   						@click="getPhone(basicConfiguration.customer_service)">联系客服</text></text>
	   			</view>
	   		</view>
	   
	   	</label>
	   
	   
	   </radio-group>
		<!-- 	<view class="flex margin-top_20rpx" style="color: rgb(153, 153, 153);">
			<text>{{step==1?'1/2':'2/2'}}</text>
		</view> -->

	</view>
	
</template>

<script>
	export default {
		components: {

		},
		data() {

			const currentDate = this.getDate({
				format: true
			});
			return {
				Uploadavatar: this.$img.Uploadavatar,
				womenticon: this.$img.womenticon,
				nanicon: this.$img.nanicon,
				userInfo: uni.getStorageSync("userInfo"),
				title: 'Hello',
				seconds: '',
				showBtn: false,
				Gender: ['男', '女'],
				currentIndex: 0,
				step: 1,
				avatarUrl: '',
				isShowBirthday: false,
				//选择的年份
				yeartime: currentDate.split('-')[0],
				//选择的月份
				monthtime: currentDate.split('-')[1],
				//选择的天数
				daytime: currentDate.split('-')[2],
				date: '',
				form: {
					birthday: '',
					sex: '1',
					avatarUrl: '',
					nickname: '',
					phone: '',
					longitude: '',
					dimension: "",
					unionId: '',
					sms_code:''

				},


				address: '',
				openid: '',
				unionid: '',
				basicConfiguration: {},
				appid: "",
				code: '',
				// 验证码校验
				codeVerification: '',
				count: null,
				disableCode: false,
				animation: '',
				agreeChecked: false,
				newUserInfo:{}
				


			}
		},
		onLoad(options) {
			
			console.log(options)
			
			   this.newUserInfo=options

	

		},
		onShow() {

		},
		methods: {
			
			toAgreement() {
				this.$refs.myPackagePopup.show({
					style: 'background-color:#fff;width:600rpx;border-radius:10rpx;padding:20rpx',
					bottomClose: true,
					shadeClose: true,
					topclose: true
				});
			},
			checkedOn2(e) {
				this.agreeChecked = !this.agreeChecked
			},
           // 验证码码倒计60秒
           countDown(seconds) {
           	this.count = seconds;
           	var countdownTimer = setInterval(() => {
           		this.count--;
           		if (this.count === 0) {
           			clearInterval(countdownTimer);
           			this.disableCode = false;
           			// 在这里可以触发验证码过期后的操作
           		}
           	}, 1000);
           },
           
           // 注册获取验证码
           async getVerificationCode() {
           	if (!this.disableCode) {
           		
           		if (/^1[3456789]\d{9}$/.test(this.form.phone)) {
           			const result = await this.$http.post({
           				url: this.$api.sendSmsRequest,
           				data: {
           				
           					phone: this.form.phone
           				}
           			});
           
           			if (result.code == 0) {
           			
           				this.disableCode = true;
           				this.countDown(60);
           			} else {
           				this.$sun.toast(result.message, 'none');
           			}
					
           		} else {
           			this.$sun.toast('请填写正确的手机号', 'none');
           		}
           	}
           },
           
			async gloginFn() {
				const result = await this.$http.post({
					url: this.$api.glogin,
					data: {
					
						phoneNumber: String(this.form.phone),
						headimgurl: this.newUserInfo.headimgurl,
						openid:this.newUserInfo.openid,
						unionid:this.newUserInfo.unionid,
						sex: this.form.sex,
						birthday: this.form.birthday,
				        nickname:this.newUserInfo.nickname,
						invite: uni.getStorageSync("invite") ?uni.getStorageSync("invite") : '',
						sms_code:this.form.sms_code
                        
					},
					headers: {

					}

				})

				if (result.code == 0) {
                  	uni.removeStorageSync('invite')
					this.$sun.toast('登录成功');
					wx.setStorageSync('userInfo', result.data);

					this.$sun.navRe('/pages/home/index');

				} else {
					this.$sun.toast(result.message,'none');
				}
			},


			
			switchGenderFn(index) {
				if (index) {
					this.form.sex = 2
				} else {
					this.form.sex = 1
				}
				this.currentIndex = index
			},
			nextFn() {



			},
			onGetPhoneNumber(e) {
				console.log("-----------------", e);
				this.getKeyByCode(e.detail.code);
				// var _that = this;
				// 用户点击了接受
				// if (e.detail.errMsg == 'getPhoneNumber:ok') {
				// 	let encryptedData = e.detail.encryptedData;
				// 	let errMsg = e.detail.errMsg;
				// 	let iv = e.detail.iv;
				// 	const code = e.detail.code;
				// 	_that.cc = code;
				// 	console.log(_that.cc)
				// 	this.getKeyByCode(_that.cc);
				// } else {
				// 	/* uni.switchTab({
				// 		url: '/pages/index/index'
				// 	}); */
				// }
			},
			// 获取手机号解密接口
			async getKeyByCode(code) {
				const result = await this.$http.post({
					url: this.$api.getPhoneCode,
					data: {
						code: code,

					}
				});
				if (result.code == 0) {
					console.log('data', result.data);
					this.form.phone = result.data.phone_info.phoneNumber;
					// uni.setStorageSync('mobile', this.mobile);
				}
			},

			getLocations() {
				console.log('123')
				uni.getLocation({
					// 将wgs84 改为 gcj02  h5提高精确度
					type: 'wgs84',
					//  geocode: true,   address：地址信息（仅App端支持，需配置geocode为true）
					success: async res => {
						console.log(res)
						this.form.longitude = res.longitude;
						this.form.dimension = res.latitude;
						// 获取当前经纬度  存缓存  在计算差距离的时候 调用
						// wx.setStorageSync('lat', this.latitude);
						// wx.setStorageSync('lng', this.longitude);
						console.log(this.form.longitude, this.form.dimension)

						// const result = await this.$sun.location({
						// 	lat: this.form.dimension,
						// 	lng: this.form.longitude,
						// 	key: this.basicConfiguration.tencent_map_key ? this.basicConfiguration
						// 		.tencent_map_key : 'SFABZ-WANWW-FISRY-3IGTF-HV7RE-YSFTI'
						// })
						
						const result = await this.$http.post({
							url: this.$api.getAddress,
							data: {
								dimension: this.form.dimension,
								longitude:this.form.longitude,
							}
						});
						if (result.code == 0) {
							 this.address = result.data.address
							console.log(result, '-------------------');
						} else {
							this.$sun.toast(result.message)
							console.log('result.message', result.message);
						}
						
						

						// this.address = result.address
						// console.log(this.address)
					},
					fail: res => {
						console.log('123', res)
						this.lat = res.latitude;
						this.lng = res.longitude;
					}
				});
			},
			// 选择头像
			onChooseAvatar(e) {
				const {
					avatarUrl
				} = e.detail;
				// console.log(avatarUrl)
				this.xixixi(avatarUrl);
			},
			// 选择日期
			bindDateChange: function(e) {
				this.isShowBirthday = true
				this.date = e.target.value;
				console.log(e.target.value)
				this.form.birthday = e.target.value
				/* 在上面声明变量，split是用来截取字段*/
				this.yeartime = this.date.split('-')[0];
				this.monthtime = this.date.split('-')[1];
				this.daytime = this.date.split('-')[2];
			},
			// 日期获取
			getDate(type) {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();
				if (type === 'start') {
					year = year - 60;
				} else if (type === 'end') {
					year = year + 2;
				}

				month = month > 9 ? month : '0' + month;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`;
			},

			handleSubmit(e) {
				this.$at.uniDoFunc({
					key: 'submit',
					success: async () => {
						this.$at.lockKey('submit');

						if (this.step == 2 && this.form.phone && this.form.longitude && this.form.dimension) {
							this.$at.releaseKey('submit');
							this.gloginFn()
						} else if (this.step == 1 && !this.form.phone) {
							this.$sun.toast('请填写手机号', 'none')
							this.$at.releaseKey('submit');
						} else if (this.step == 1) {
							// 提交到接口
							const val = e.detail.value;
							this.form.nickname = val.nickname;

							console.log(this.form)
							this.$at.releaseKey('submit');

							if (!this.form.sex) {
								this.$sun.toast('请选择性别', 'none')
							} else if (!this.form.birthday) {
								this.$sun.toast('请选择生日日期', 'none')
							} else if(!this.form.sms_code){
								this.$sun.toast('请输入验证码', 'none')
							}else if(!this.agreeChecked){
							
									this.$sun.toast('请先阅读并同意《用户注册协议》', 'none');
									this.animation = 'shake';
									setTimeout(() => {
										this.animation = '';
									}, 1300);
									this.$at.releaseKey('submit');
								
							}
							else{
								this.gloginFn()
							}
						}

					}
				});








			},
			async getOpenidAndSessionKeyFn(code) {
				const result = await this.$http.post({
					url: this.$api.getOpenidAndSessionKey,
					data: {
						code: code,

					}
				});
				if (result.code == 0) {
					console.log('data', result.data);
					this.openid = result.data.openid
					// this.unionid=result.data.unionid

					// uni.setStorageSync('mobile', this.mobile);
				}
			},

			// getUserProfile() {
			// 	setTimeout(() => {
			// 		uni.request({
			// 			url: this.$api.testLogin,
			// 			method: 'POST',
			// 			data: {
			// 				phoneNumber: String(this.form.phone),

			// 			},
			// 			success: async res => {
			// 				console.log(res)
			// 				if (res.data.code == 0) {

			// 					// 当前状态 为true的时候不清除

			// 					this.$sun.toast('登录成功');
			// 					wx.setStorageSync('userInfo', res.data.data);

			// 					this.$sun.navRe('/pages/home/home');

			// 				} else {
			// 					this.$sun.toast(res.data.message);
			// 				}

			// 			},
			// 			fail: err => {
			// 				uni.showModal({
			// 					title: '错误',
			// 					content: `访问公众平台接口失败, 错误: invalid appsecret, view more at http://t.cn/RAEkdVq, hints: [ req_id: WeMfdZyFe-D3JW7 ],错误详情：无效的appsecret`,
			// 					showCancel: false
			// 				});
			// 			},
			// 			complete: info => {
			// 				// 由于wx.getUserProfile被删除了，所以获取不到res.user
			// 				// wx.setStorageSync('userInfo', user);
			// 			}
			// 		});
			// 	}, 500);

			// },

			getUserProfile() {
				if (this.form.phone) {
					wx.login({
						provider: 'weixin',
						success: async res => {
							console.log(res)

							const result = await this.$http.post({
								url: this.$api.getOpenidAndSessionKey,
								data: {
									code: res.code,

								}
							});
							if (result.code == 0) {
								console.log('data', result.data);
								this.openid = result.data.openid
								this.unionid = result.data.unionid
								setTimeout(() => {
									uni.request({
										url: this.$api.userLogin,
										method: 'POST',
										data: {
											phoneNumber: String(this.form.phone),
											nickname: this.form.nickname,
											avatarUrl: this.form.avatarUrl,
											sex: this.form.sex,
											birthday: this.form.birthday,
											longitude: this.form.longitude,
											dimension: this.form.dimension,
											unionid: this.unionid,
											openid: this.openid,
											invite: uni.getStorageSync('pid') ? uni
												.getStorageSync('pid') : ''

											/*  * 新增微信用户
											 * @param openid
											 * @param avatar 头像
											 * @param nickname 昵称
											 * @param dy_uid 抖音uid */
											// 微信用户opendid
											// openid: wx.getStorageSync('openid'),
											// unionid:openInfo.result.unionid,
											// // 微信用户昵称
											// // nickname: user.nickName,
											// // 独立小程序需要
											// nickname: this.nickname ? this.nickname : '默认昵称',
											// // 微信用户头像
											// avatar: this.avatarUrl ? this.avatarUrl :
											// 	'/static/avatar.png',
											// 分销pid
											// pid : pid
											// pid: uni.getStorageSync('pid') ? uni.getStorageSync('pid') : null,
											// 站点id
											// siteId: String(wx.getStorageSync('siteId')),
										},
										success: async res => {
											console.log(res)
											if (res.data.code == 0) {

												// 当前状态 为true的时候不清除

												this.$sun.toast('登录成功');
												wx.setStorageSync('userInfo', res.data
													.data);

												this.$sun.navRe('/pages/home/index');

											} else {
												this.$sun.toast(res.data.message);
											}

										},
										fail: err => {
											uni.showModal({
												title: '错误',
												content: `访问公众平台接口失败, 错误: invalid appsecret, view more at http://t.cn/RAEkdVq, hints: [ req_id: WeMfdZyFe-D3JW7 ],错误详情：无效的appsecret`,
												showCancel: false
											});
										},
										complete: info => {
											// 由于wx.getUserProfile被删除了，所以获取不到res.user
											// wx.setStorageSync('userInfo', user);
										}
									});
								}, 500);
							}
							// this.getOpenidAndSessionKeyFn(res.code)


						}
					});
				} else {
					this.$sun.toast('请先完成获取手机号');
				}
			},
			async xixixi(avatarUrl) {



				uni.uploadFile({
					url: this.$api.upload, //仅为示例，非真实的接口地址
					filePath: avatarUrl,

					name: 'file',
					formData: {

					},
					success: (res) => {
						console.log(res)
						if (res.statusCode == 200) {
							console.log('uploadImage success, res is:', res)

							uni.showToast({
								title: '上传成功',
								icon: 'success',
								duration: 1000
							})
							this.upLoadStatus = '上传成功'
							this.form.avatarUrl = JSON.parse(res.data).data.url

						}



					},
					fail: (err) => {
						if (this.pageVisible) {
							console.log('uploadImage fail', err);
							uni.hideLoading();
							uni.showModal({
								content: err.errMsg,
								showCancel: false
							});
						}
					},
				});

			},
		}
	}
</script>

<style lang="less" scoped>
	.setUpChildLogin {

		height: 100vh;
		position: relative;
		padding: 60rpx 60rpx 0 80rpx;
		background-repeat: no-repeat;
		background-size: cover;
		background-image: url('http://yunhunjian123.oss-cn-shanghai.aliyuncs.com/2024-06-18/a9172202406181027426439.png');
         .iphone {
         	position: relative;
         
         }
		 /* 隐私协议 start */
		 .radioText {
		 	margin: 68rpx 0;
		 }
		 
		 .agree {
		 	color: #666;
		 
		 	text {
		 		color: #1890ff;
		 		// color: #19c866;
		 	}
		 }
		 
		 .animation {
		 	width: 10rem;
		 	height: 2rem;
		 	background: #ffffff;
		 	margin-top: 0.5rem;
		 }
		 
		 .animation-shake {
		 	animation: shake 0.3s !important;
		 }
		 
		 @keyframes shake {
		 
		 	0%,
		 	100% {
		 		transform: translateX(0);
		 	}
		 
		 	10% {
		 		transform: translateX(-9px);
		 	}
		 
		 	20% {
		 		transform: translateX(8px);
		 	}
		 
		 	30% {
		 		transform: translateX(-7px);
		 	}
		 
		 	40% {
		 		transform: translateX(6px);
		 	}
		 
		 	50% {
		 		transform: translateX(-5px);
		 	}
		 
		 	60% {
		 		transform: translateX(4px);
		 	}
		 
		 	70% {
		 		transform: translateX(-3px);
		 	}
		 
		 	80% {
		 		transform: translateX(2px);
		 	}
		 
		 	90% {
		 		transform: translateX(-1px);
		 	}
		 }
		.avatar-wrapper {
			padding: 0;
			width: 240rpx;
			border-radius: 8px;
			margin-bottom: 40px;
			color: #9b9b9b;
			background: transparent;

			.loginAvatar {
				margin-top: 50rpx;
				width: 200rpx;
				height: 200rpx;
				border-radius: 50%;
			}

		}

		.male {
			width: 280rpx;
			height: 108rpx;
			box-sizing: border-box;
			border: 2rpx solid rgb(108, 2, 250);
			border-radius: 124rpx;

			background: rgb(237, 234, 255);
		}

		.female {
			width: 280rpx;
			height: 108rpx;
			box-sizing: border-box;
			border-radius: 124rpx;

			background: rgb(247, 247, 249);

			background: rgb(237, 234, 255);
		}

		.genderImg {
			width: 41.26rpx;
			height: 41.26rpx;
			margin-right: 30rpx;
		}

		.birthday {

			height: 96rpx;
			border-radius: 124rpx;

			background: #f5f5f9;
		}

		.getPhone {
			height: 96rpx;
			border-radius: 124rpx;

			background: #f5f5f9;
			position: relative;

			.ckPhone {
				height: 96rpx;
				line-height: 100rpx;
				width: 220rpx;
				background-color: transparent;
				color: #000;
			}
			
			.verificationCode {
				z-index: 999;
				position: absolute;
				right: 0;
				text-align: center;
				width: 170rpx;
				height: 65rpx;
				line-height: 65rpx;
				border-radius: 100rpx;
				font-size: 20rpx;
				background: #7D5CF7;
				color: #fff;
			}
		}

		input {
			text-align: center;
		}

		.edit {

			height: 96rpx;
			background: rgb(246, 248, 255);



		}

		.next {
			width: 450rpx;
			margin: 66rpx 60rpx 0;
			height: 100rpx;
			border-radius: 130rpx;
			color: #fff;
			line-height: 100rpx;
			background: linear-gradient(80.35deg, rgb(171, 81, 255) 0.206%, rgb(120, 93, 246) 99.688%);
		}

	}
</style>